#include "checkoutdialog.h"
#include "ui_checkoutdialog.h"

#include "configutil.h"

#include <QFileInfo>
#include <QPushButton>

CheckoutDialog::CheckoutDialog(QWidget *parent)
    : QDialog(parent)
    , ui(new Ui::CheckoutDialog)
    , m_type(Sync)
{
    ui->setupUi(this);

    QPushButton *btn = ui->buttonBox->button(QDialogButtonBox::Ok);
    if (btn) btn->setEnabled(false);
    
    QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
    env.insert("REPO_TRACE", "0");
    m_process.setProcessEnvironment(env);
    m_process.setProcessChannelMode(QProcess::MergedChannels);

    connect(&m_process, qOverload<int>(&QProcess::finished), this, [this](int exitCode)
    {
        if (exitCode == 0)
        {
            emit checkouted();
            setWindowTitle("repo 检出完成: " + m_path);
        } else {
            setWindowTitle("repo 检出异常: " + m_process.errorString());
        }

        if (ui) {
            QPushButton *btn = ui->buttonBox->button(QDialogButtonBox::Ok);
            if (btn) btn->setEnabled(true);
        }
    });

    connect(&m_process, &QProcess::readyRead, this, [this]()
    {
        QString output;
        output = m_process.readAll();
        ui->repo_sync_content->appendPlainText(output);
    });

    m_procinfo_timer.setInterval(1000);
    m_procinfo.getLinuxNetworkDownload(); // first clean speed;
    connect(&m_procinfo_timer, &QTimer::timeout, this, [this](){
        double downSpeed = 0;
        ProcInfoUtils::SpeedRateUnit unit;

        unit = ProcInfoUtils::SpeedRateByte;
        long download = m_procinfo.getLinuxNetworkDownload();
        QString downUnit = m_procinfo.autoRateUnits(download, unit, downSpeed);
        //↓:
        QString down_speed_text =  QString("↓:%1").arg(downSpeed, 0, 'f', 2, QLatin1Char(' ')) + downUnit;
        ui->label->setText(down_speed_text);
    });
    m_procinfo_timer.start();
}

CheckoutDialog::~CheckoutDialog()
{
    delete ui;
    ui = nullptr;
}

void CheckoutDialog::setWorkdir(const QString &newWorkdir)
{
    m_workdir = newWorkdir;
}

void CheckoutDialog::setPath(const QString &newPath)
{
    m_path = newPath;
    m_type = Simple;
    ui->listWidget->hide();
}

void CheckoutDialog::setPaths(const QStringList &newPaths)
{
    m_paths = newPaths;
    m_type = Multiple;
    ui->listWidget->addItems(m_paths);
}

void CheckoutDialog::start()
{
    // if (ConfigUtil::getAppRepoConfig().isEmpty() == false)
    // {
    //     ui->repo_sync_content->setPlainText(QString("-- repo sync %1 -- \n").arg(m_path));

    //     auto dir = QFileInfo(ConfigUtil::getAppRepoConfig()).absolutePath();

    //     QProcess process;
    //     process.setProgram(ConfigUtil::getAppRepoConfig());
    //     process.setArguments(QStringList("sync") << m_path);
    //     process.start();
    //     process.waitForFinished();

    //     ui->repo_sync_content->appendPlainText(process.readAllStandardOutput() + "\n");
    // }


    QString once_info("-- repo %1 -- \n");
    QStringList arguments("sync");
    switch (m_type) {
    case Simple:
        arguments << m_path;
        break;
    case Multiple:
        arguments << m_paths << QString("-j%1").arg(m_paths.count() > 25 ? 25 : m_paths.count());
        break;
    case Sync:
        arguments << "-j4";
        break;
    case SyncDetach:
        arguments << "-j4" << "--detach";
        break;
    }
    arguments << "-v";
    once_info = once_info.arg(arguments.join(" "));
    ui->repo_sync_content->setPlainText(once_info);
    m_process.setWorkingDirectory(m_workdir);
    m_process.setProgram(ConfigUtil::getAppRepoConfig());
    m_process.setArguments(arguments);
    m_process.start();
}

void CheckoutDialog::setType(Type newType)
{
    m_type = newType;
}

